package com.offcn.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * c3p0连接池连接数据库
 */
public class C3p0Utils {
    private static ThreadLocal<Connection> t = new ThreadLocal<>();
    // ThreadLocal解决并发编程下的线程不安全，可以在指定线程馁存储数据
    private static ComboPooledDataSource dataSource;
    // 新建连接池
    static{
        dataSource = new ComboPooledDataSource();
    }//静态代码块，随着类的加载而加载而且只执行一次
    //1、获取连接对象
    public static Connection getConnection() throws SQLException {
        Connection conn =  t.get();
        //获得正在跑的线程，即是连接
        if(conn==null){
            t.set(dataSource.getConnection());
            //无连接则获取连接
            conn = t.get();
        }
        return conn;
    }
    //2、归还连接
    public static void release(){
        Connection conn = t.get();
        t.remove();
        try {
            conn.close();//归还到连接池
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}
